import { useCallback, useEffect, useState, useRef } from "react";
import { message, Form } from "antd";

import { hiprint } from "vue-plugin-hiprint";
import { getAllPrinter } from "@/utils/print.jsx";
import {
	setPrinterName,
	getPrinterName,
	getCurrentUser,
	getExpressRelativePrinter,
	setExpressRelativePrinter
} from "@/utils/authority";
import { cloneDeep } from "lodash";
import { defaultTemplateMap } from './hiprint/providers.js';



// 唯一码模板接口
import request from "@/utils/request";
import { stringify } from "qs";

export async function getPrintTemp(params) {
	// return request(`/new-wms/fmcgpurchases/getPrintTemp?${stringify(params)}`);
	return request(`/new-wms/fmcgpurchases/getPrintTemp`, {
		method: "post",
		data: params
	});
}
let hiprintTemplate, runner;
export const usePrintUniqueCode = props => {
	const uniqueCodeKey = props?.uniqueCodeKey || "uniqueCode";
	const init = !!props?.init;
	const [form] = Form.useForm();
	const [configObj, setConfigObj] = useState({});
	const [printer, setPrinter] = useState("");
	const [printedArr, setPrintedArr] = useState([]);
	const [printData, setPrintData] = useState([]);
	const [template, setTemplate] = useState([]);
	const [updateList, setUpdateList] = useState([]);

	const taskCount = useRef(-1);
	const firstFlag = useRef(undefined);//是否插入第一张供应商的不充分标记
	// const [taskSuccessCount, setTaskSuccessCount] = useState(0);
	// const [taskFailedCount, setTaskFallCount] = useState(0);
	// const [taskSuccessList, setTaskSuccessList] = useState([]);
	// const [taskFailedList, setTaskFailedList] = useState([]);
	const printSuccessCallback = props.printSuccessCallback
		? props.printSuccessCallback
		: async params => {
				console.log("打印成功的记录更新 printSuccessCallback", params);
				taskCount.current--;
				console.log(taskCount.current, "taskCount.current");
				// await setTaskSuccessCount(taskSuccessCount + 1);
				// await setTaskSuccessList([...taskSuccessList, params]);
				return new Promise((resolve, reject) => {
					resolve({});
				});
			};
	const printFailedCallback = props.printFailedCallback
		? props.printFailedCallback
		: async list => {
				console.log("打印失败的记录更新 printFailedCallback", list);
				taskCount.current--;
				// await setTaskFallCount(taskFailedCount + 1);
				// await setTaskSuccessList([...taskFailedList, list]);
				// if (res?.printStatus?.length > 0) {
				// 	message.warning(res.printStatus.map(e => `${e.documentID}打印失败:${e.detail}`).join(","));
				// } else if (res?.results?.length > 0) {
				// 	message.warning(res.results.map(e => ` ${e.taskID}打印${e.success ? "成功" : "失败"}:${e.failureReason}`).join(","));
				// } else if (res.msg) {
				// 	message.warning(`${list.orderSn}  ${res?.msg}`);
				// } else {
				// 	message.warning(list.orderSn + "打印失败");
				// }
				return new Promise((resolve, reject) => {
					resolve({});
				});
			};
	const [printCodes, setPrintCodes] = useState([]);
	const latestRealPrintFunc = useRef();

	useEffect(() => {
		console.log(taskCount.current, "taskCount");
		if (taskCount.current === 0) {
			console.log("打印结束，执行回调");
			props.callback && props.callback({ printData: printData });
			taskCount.current = -1;
		}
	}, [taskCount.current]);
	const getPrintDataFunc = async rows => {
		return new Promise((resolve, reject) => {
			console.log(rows, "rowsss");
			rows.forEach(i => {});
			// printType 1:打印全部；2：打印筛选项;3:打印所选项
			if (props.printType == 3) {
				console.log(rows, "rows");
				const list = [];
				list.push(rows?.[0][uniqueCodeKey]);
				console.log(list, "list");
				getPrintTemp({ codes: list }).then(({ data }) => {
					setPrintCodes(rows);
					const selectedOneTemple = { panels: [data.panels[0]] };
					setTemplate(selectedOneTemple);
					resolve([selectedOneTemple, rows]);
				});
				// getAllData(rows).then(allData => {
				// 	console.log(allData, "allData");

				// 	if (allData?.length > 0) {
				// 		setPrintCodes(rows);
				// 		const selectedOneTemple = { panels: [allData[0]] };
				// 		setTemplate(selectedOneTemple);
				// 		resolve([selectedOneTemple, rows]);
				// 	}
				// });
			} else if (props.printType == 2) {
				console.log(rows, "rows");
				const list = [];
				list.push(rows?.[0][uniqueCodeKey]);
				console.log(list, "list");
				getPrintTemp({ codes: list }).then(({ data }) => {
					setPrintCodes(rows);
					const selectedOneTemple = { panels: [data.panels[0]] };
					setTemplate(selectedOneTemple);
					resolve([selectedOneTemple, rows]);
				});
				// getAllData(rows).then(() => {
				// 	console.log(allData, "allData");
				// 	// console.log(results, "resultssssssssssssssssss");
				// 	if (allData.length > 0) {
				// 		setPrintCodes(rows);
				// 		const selectedOneTemple = { panels: [allData[0]] };
				// 		setTemplate(selectedOneTemple);
				// 		resolve([selectedOneTemple, rows]);
				// 	}
				// });
			} else {
				getPrintTemp({ codes: rows.map(e => e[uniqueCodeKey]) }).then(({ data }) => {
					setPrintCodes(rows);
					const selectedOneTemple = { panels: [data.panels[0]] };
					setTemplate(selectedOneTemple);
					resolve([selectedOneTemple, rows]);
				});
			}
		});
	};
	const printAction = ([__template, __printData, printer]) => {
		if (__printData && __printData.length) {
			const tasks = [];
			__printData.map((printDataItem, index) => {
				if(props.needPrintFirstStore && !printDataItem.isSingle && firstFlag.current != printDataItem.supplierName){//插入第一张供应商
					firstFlag.current = printDataItem.supplierName;
					tasks.push(done => {
						firstStorePrint(done, printDataItem, printer);
					});
				}
				tasks.push(done => {
					latestRealPrintFunc.current(runner, done, index, printer);
				});
			});
			runner.addMultiple(tasks);
			message.success(`即将打印${__printData.length}个条码，请等待`);
		} else {
			return message.info("打印数据为空");
		}
	};

	const firstStorePrint = (done, printItem, printer) => {
		hiprintTemplate = new hiprint.PrintTemplate({ template: JSON.parse(defaultTemplateMap[0]) });
		hiprintTemplate.on("printSuccess", done);
		hiprintTemplate.on("printError", done);
		hiprintTemplate.print2(printItem, { printer });
	}

	//打印队列渲染输出
	const realPrint = (runner, done, index, printer) => {
		console.log(runner, index, "ssssssssssss");
		const printDataItem = printData[index];
		if (!printDataItem || !template) {
			return message.error("未获取到唯一码模板");
		}

		hiprintTemplate = new hiprint.PrintTemplate({ template });
		console.log(hiprintTemplate, "hiprintTemplate");

		hiprintTemplate.on("printSuccess", async function () {
			console.log("printSuccess");
			let list = [];
			list.push(printDataItem);
			setPrintedArr(list);
			await printSuccessCallback(list);
			// 打印成功后请求接口通知后端修改打印状态
			// props.callback && props.callback(printData);
			// props.printUpdateRequest({ code: printDataItem.uniqueCode }).then(({ res }) => {});

			done();
		});
		hiprintTemplate.on("printError", async function () {
			console.log(runner?.tasks?.list, "printError,runner?.tasks?.list");
			await printFailedCallback(runner?.tasks?.list);

			if (!runner?.tasks?.list?.length) {
				setPrintedArr([]);
			}
			done();
		});
		hiprintTemplate.print2(printDataItem, { printer });
	};
	latestRealPrintFunc.current = realPrint; //手动用ref保存最新的realPrint 然后通过他调用realPrint

	/**
	 *
	 * @param {*} printData 数组[], 数组内的元素如下
	 * {uniqueCode:"条形码",  codeSN:"序号" ,orderGoodsCount:"订单商品数量",orderGoodsName:"订单商品名称",orderGoodsSpec:"订单规格属性",salesOrderSn:"销售出库单号"}
	 */
	const printUniqueCode = rows => {
		setPrintData(cloneDeep(rows));
		if (!runner) {
			runner = new TaskRunner();
			runner.setConcurrency(1); // 同时执行数量
		}
		const printerConfigs = getExpressRelativePrinter();
		const uniqueCodePrinter = printerConfigs["唯一码"];
		if (!uniqueCodePrinter) {
			return message.warning("请先设置唯一码关联的打印机");
		}
		getAllPrinter(currentPrinters => {
			if (currentPrinters.includes(uniqueCodePrinter)) {
				getPrintDataFunc(rows).then(printAction);
			} else {
				return message.warning(`唯一码关联的打印机${uniqueCodePrinter}未开启`);
			}
		});
	};

	const [printerList, setPrinterList] = useState([]); //打印机列表
	const [uniqueCodePrinter, setUniqueCodePrinter] = useState(""); //唯一码打印机

	const initPrint = rows => {
		firstFlag.current = undefined;
		taskCount.current = rows.length;
		console.log(rows, "rows"); // 设置打印任务总数量
		setPrintData(cloneDeep(rows));
		if (!runner) {
			runner = new TaskRunner();
			runner.setConcurrency(1); // 同时执行数量
		}
		const printerConfigs = getExpressRelativePrinter();
		const __uniqueCodePrinter = printerConfigs["唯一码"];
		setUniqueCodePrinter(__uniqueCodePrinter);
		getAllPrinter(currentPrinters => {
			setPrinterList(currentPrinters);
		});
		getPrintDataFunc(rows);
	};

	useEffect(() => {
		// 从缓存中取出快递和打印机配置数据
		const obj = getExpressRelativePrinter() || {};
		setConfigObj(obj);
		form.setFieldsValue({ ...obj });
	}, []);

	const setUniqueCodeRelativePrinter = name => {
		setExpressRelativePrinter({
			...configObj,
			["唯一码"]: name
		});
	};

	return {
		// 一步打印，不弹窗
		printUniqueCode, //

		// 以下是分步骤进行的，参见
		// src\views\purchase\FmcmPurchase\component\PrintModal.jsx
		initPrint,
		printData,
		template,
		printerList,
		uniqueCodePrinter,
		configObj,
		getPrintDataFunc,
		printAction,
		getExpressRelativePrinter,
		setUniqueCodeRelativePrinter
	};
};
